(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:RoleCtrl
     * @description
     * # RoleCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('RoleCtrl', RoleCtrl);

    RoleCtrl.$inject = ['$scope', 'dataService', '$location', '$timeout', 'helper', '$rootScope'];

    function RoleCtrl($scope, dataService, $location, $timeout, helper, $rootScope) {
        //角色显示
        $scope.listAction = function() {
            $scope.itemsTotal = 0;
            $scope.pageSize = 5;
            $scope.getRoleList(1);
        }
        $scope.fujiaAction = function() {
            $scope.role_id = $location.search().role_id;
            $scope.fujiaget();
        }

        $scope.fujiaget = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize ? $scope.pageSize : 200,
                role_id: $scope.role_id,
            };

            dataService.phpPermissionGet(query).then(function(list) {
                if (list) {
                    var newitems = list.permission_list;
                    $scope.permission_id_list = [];
                    $scope.permission_list = {};
                    _.map(newitems, function(da, key) {
                        $scope.permission_id_list.push(da.pid);
                        $scope.permission_list[da.pid] = da;
                    });
                    $scope.total_count = list.total_count;
                }
            });
        }

        $scope.phpPermissionAdd = function(role_id) {
                async.map($scope.permission_list, function(da, callback) {
                    if (!da.id) {
                        var data = {
                            "role_id": role_id,
                            "pid": da.pid,
                        }
                        saveresource(data).then(function(da) {
                            if (da) {
                                callback(da, null);
                            } else {
                                callback(null, null);
                            }
                        });
                    } else {
                        callback(null, null);
                    }
                }, function(e, r) {
                    helper.myAlert("success", "#/role/list");
                });
            }
            //附加权限组件 回调方法
        $scope.fujiasaveresource = function(resoucres) {
            console.error("resoucres", resoucres);
            _.map(resoucres, function(da, key) {
                if ($scope.permission_list) {
                    if (!$scope.permission_list[da]) {
                        $scope.permission_list[da] = { id: 0, role_id: 0, pid: da };
                    }
                } else {
                    $scope.permission_list = {};
                    $scope.permission_list[da] = { id: 0, role_id: 0, pid: da };
                }

            });
            console.error("resoucres", resoucres, $scope.permission_list);
        }

        $scope.permissionsSplice = function(id, key) {
            helper.myConfirm("确认删除吗", function() {
                if (id) {
                    var data = { 'id': id };
                    dataService.phpPermissionDelete(data).then(function(result) {
                        if (result.id) {
                            helper.myAlert("success", null, null, function() {
                                del();
                            });
                        } else {
                            helper.myAlert("error:" + result);
                        }
                    });
                } else {
                    del();
                }
            });

            function del() {
                $timeout(function() {
                    delete $scope.permission_list[key];
                    _.map($scope.permission_id_list, function(da, k) {
                        if (da == key) {
                            $scope.permission_id_list.splice(k, 1);
                        }
                    });
                    // console.error($scope.permission_id_list,$scope.permission_list,key);
                });
            }

        }

        function saveresource(data) {
            return dataService.phpPermissionAdd(data).then(function(list) {
                if (!list.Msg) {
                    return list;
                } else {
                    // rmAlert();
                    // helper.myAlert(list.Msg);
                    return;
                }
            });
        }
        $scope.search = function() {
            // console.log("keyword:", $scope.keyword);
        }

        //设为客服
        $scope.setKefu = function(role, a) {
            role.is_forward_msg = a;
            dataService.roleAdd(role).then(function(result) {
                $scope.getRoleList();
            });
        }

        $scope.back = function(permissions) {

            permissions = _.uniq(permissions);
            console.error("permissions", permissions);
            // return;
            if (permissions) {
                $scope.item.permissions = [];
                $scope.item.permissions = permissions;
            }

        }

        //获取角色列表
        $scope.getRoleList = function(pageNo) {

                var query = {
                    page_no: pageNo ? pageNo : "1",
                    page_size: $scope.pageSize
                };
                if ($scope.name) {
                    query.query = { "name": $scope.name };
                }

                dataService.roleGet(query).then(function(list) {
                    if (list) {
                        $scope.itemslist = list.roles;
                        $scope.itemsTotal = list.total_count;
                    }
                });
            }
            //添加
        $scope.addAction = function() {
                var role_id = $location.search().role_id;
                var chosed_type = $location.search().chosed_type
                $scope.chosedType = '2';
                $scope.item = {};
                $scope.initassembly();
                if (role_id) {
                    $scope.role_id = role_id;
                    if (chosed_type) {
                        $scope.chosedType = chosed_type;
                    }
                    $scope.roleOne();
                    // $scope.roleuserList();
                } else {
                    $scope.item = { name: "", is_super_admin: false, };
                    $scope.user_wxstore = [];
                    $scope.item.permissions = $scope.initpermissions;
                }
            }
            //初始化权限组件
        $scope.initassembly = function() {
            $scope.initpermissions = [{
                action: ["get", "add", "update"],
                identity: "/rest/v1/store/",
                name: "店铺",
            }, {
                action: ["get", "add", "update"],
                identity: "/rest/v1/seller/current/",
                name: "当前用户",
            }, {
                action: ["get", "add", "update"],
                identity: "/rest/v1/shopconfig/",
                name: "店铺配置",
            }, {
                action: ["get"],
                identity: "/rest/v1/role/",
                name: "角色",
            }, {
                action: ["get"],
                identity: "/rest/v1/wxproxy/",
                name: "微信透明代理",
            }, {
                action: ["add"],
                identity: "/rest/v1/formid/",
                name: "FormId添加",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/dhf/store/related/apps/",
                name: "查询授权小程序",
            }, {
                action: ["get"],
                identity: "/rest/v1/partner/",
                name: "查询公司",
            }, {
                action: ["get"],
                identity: "/rest/v1/seller/basicinfo/",
                name: "商家基本信息",
            }, {
                action: ["get"],
                identity: "/rest/v1/buyer/basicinfo/",
                name: "买家基本信息",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/wxappcfg/",
                name: "小程序配置",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/attach/",
                name: "附件",
            }];

            $scope.kfinit = [{
                action: ["get", "update"],
                identity: "/rest/v1/autorspcfg/",
                name: "自动回复设置",
            }, {
                action: ["get", "update", "add"],
                identity: "/rest/v1/chatrecord/",
                name: "聊天消息",
            }, {
                action: ["get"],
                identity: "/rest/v1/chatsession/",
                name: "查询会话",
            }];

            $scope.hexiaoinit = [{
                action: ["get"],
                identity: "/rest/v1/php/dhf/gift/details/",
                name: "礼物详情",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/dhf/gift/",
                name: "礼物",
            }, {
                action: ["update"],
                identity: "/rest/v1/php/dhf/gift/destroy/",
                name: "礼物详情核销",
            }, {
                action: ["get"],
                identity: "/rest/v1/seller/basicinfo/",
                name: "商家基本信息",
            }, {
                action: ["get"],
                identity: "/rest/v1/buyer/basicinfo/",
                name: "买家基本信息",
            }];

            $scope.jlinit = [{
                action: ["add", "delete", "get", "update"],
                identity: "/rest/v1/php/dhf/class/category/",
                name: "课程分类",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/dhf/class/",
                name: "课程",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/dhf/class/details/",
                name: "课程详情",
            }];

            $scope.zjdinit = [{
                action: ["delete", "get", "update"],
                identity: "/rest/v1/php/dhf/store/pickpoint/",
                name: "发货点",
            }, {
                action: ["update"],
                identity: "/rest/v1/php/dhf/order/pickpoint/",
                name: "订单转单",
            }];

            $scope.dyinit = [{
                action: ["delete", "get", "add", "update"],
                identity: "/rest/v1/print/",
                name: "打印模板",
            }, {
                action: ["get"],
                identity: "/rest/v1/printpub/",
                name: "公用打印模版",
            }];

            $scope.ordershinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/returnform/",
                name: "售后单",
            }, {
                action: ["update"],
                identity: "/rest/v1/returnform/status/",
                name: "售后单状态",
            }];

            $scope.iteminit = [{
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/category/",
                    name: "类目",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/item/",
                    name: "商品",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/skutype/",
                    name: "SKU类型",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/faretemp/",
                    name: "运费模板",
                },
                {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/pickpoint/",
                    name: "自提点",
                },
                {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/php/dhf/item/praise/",
                    name: "点赞",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/php/dhf/comments/",
                    name: "评价",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/member/",
                    name: "用户信息",
                }
            ];

            $scope.yxinit = [{
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/php/dhf/gift/",
                    name: "礼物",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/r/rest/v1/php/dhf/gift/details/",
                    name: "礼物详情",
                }, {
                    action: ["get", "update", "delete", "add"],
                    identity: "/rest/v1/php/dhf/daka/",
                    name: "打卡",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/php/dhf/gift/baobiao/",
                    name: "礼物详情报表",
                },
                {
                    action: ["update", "get"],
                    identity: "/rest/v1/php/dhf/gift/destroy/",
                    name: "礼物详情核销",
                }
            ];
            $scope.fjiteminit = ["78", "79", "80", "81", "82", "83", "84", "85", "86"];

            $scope.fjorderinit = ["76", "64", "73", "97", "100", "101", "107", "112"];

            $scope.fjzdyinit = ["91", "92", "93", "94", "95", "96", "97", "102"];



            $scope.orderinit = [{
                    action: ["get", "update"],
                    identity: "/rest/v1/order/",
                    name: "订单",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/php/dhf/store/pickpoint/",
                    name: "自提点",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/member/",
                    name: "用户信息",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/php/dhf/pintuan/detail/",
                    name: "拼团详情",
                }, {
                    action: ["get"],
                    identity: "/rest/v1/print/",
                    name: "打印模板",
                }, {
                    action: ["update"],
                    identity: "/rest/v1/order/service/",
                    name: "售后申请",
                }, {
                    action: ["add"],
                    identity: "/rest/v1/pay/refund/",
                    name: "购物退款",
                },
                {
                    action: ["update"],
                    identity: "/rest/v1/php/dhf/order/pickpoint/",
                    name: "订单转单",
                }, {
                    action: ["update"],
                    identity: "/rest/v1/order/delivery/",
                    name: "订单发货",
                },
                {
                    action: ["update"],
                    identity: "/rest/v1/order/delivery/",
                    name: "订单发货",
                }, {
                    action: ["update"],
                    identity: "/rest/v1/order/discount/",
                    name: "	更新折扣",
                }, {
                    action: ["add"],
                    identity: "/rest/v1/customs/",
                    name: " 推送支付单1",
                }, {
                    action: ["add"],
                    identity: "/rest/v1/customs/repush/",
                    name: " 推送订单",
                }, {
                    action: ["add"],
                    identity: "/rest/v1/php/dhf/exportcsv/order/",
                    name: "导出CSV",
                }
            ];

            $scope.tixianinit = [{
                action: ["get"],
                identity: "/v1/php/dhf/withdrawal/log/",
                name: "提现",
            }];

            $scope.chongzhiinit = [{
                action: ["get"],
                identity: "/rest/v1/balancelog/",
                name: "余额日志",
            }];

            $scope.mianfuinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/dhf/mianfu/",
                name: "面付",
            }];

            $scope.fjmianfuinit = ["64", "73"];

            $scope.ordershinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/returnform/",
                name: "售后单",
            }, {
                action: ["update"],
                identity: "/rest/v1/returnform/status/",
                name: "售后单状态",
            }];

            $scope.dzinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/activity/",
                name: "优惠活动",
            }, {
                action: ["get"],
                identity: "/rest/v1/memberlevel/",
                name: "用户信息",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["add"],
                identity: "/rest/v1/php/dhf/nsq/common/",
                name: "发消息",
            }];

            $scope.dzinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/activity/",
                name: "优惠活动",
            }, {
                action: ["get"],
                identity: "/rest/v1/memberlevel/",
                name: "用户信息",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["add"],
                identity: "/rest/v1/php/dhf/nsq/common/",
                name: "发消息",
            }];

            $scope.msinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/v1/php/dhf/mjs/activity/",
                name: "满送活动",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/dhf/mjs/activity/item/",
                name: "满送活动详情",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["add", "get"],
                identity: "/rest/v1/php/dhf/coupons/person/",
                name: "优惠券",
            }, {
                action: ["get"],
                identity: "/rest/v1/member/",
                name: "用户信息",
            }];

            $scope.mzinit = [{
                action: ["get"],
                identity: "/rest/v1/php/dhf/mjs/activity/item/",
                name: "满送活动详情",
            }];

            $scope.fjmzinit = ["6", "1", "102"];

            $scope.kjinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/bargainrule/",
                name: "砍价规则",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/bargainactivity/",
                name: "砍价活动",
            }];

            $scope.yfinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/faretemp/",
                name: "运费模板",
            }];

            $scope.yfinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/faretemp/",
                name: "运费模板",
            }];

            $scope.kqinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/cardlist/",
                name: "卡券列表",
            }];

            $scope.ptinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/php/dhf/pintuan/",
                name: "拼团规则",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/dhf/pintuan/activity/",
                name: "拼团活动",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/dhf/pintuan/detail/",
                name: "拼团详情",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["get"],
                identity: "/rest/v1/member/",
                name: "用户信息",
            }];

            $scope.kjinit = [{
                action: ["get"],
                identity: "/rest/v1/bargainrule/",
                name: "砍价规则",
            }, {
                action: ["get"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["get"],
                identity: "/rest/v1/bargainactivity/",
                name: "砍价活动",
            }];

            $scope.fjkjinit = ["6", "1", "102"];

            $scope.fjjcinit = ["20", "21", "42", "45", "46", "48", "58", "64", "76", "55", "73", "110", "111", "160"];

            $scope.fjwmsinit = ["103", "104", "105", "107", "106", "108", "109", "110", "131", "132", "140", "141", "142"];

            $scope.fjfzinit = ["122", "123", "124", "128", "129", "130"];

            $scope.jcinit = [{
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/category/",
                name: "类目",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/item/",
                name: "商品",
            }, {
                action: ["get", "update"],
                identity: "/rest/v1/order/",
                name: "订单",
            }, {
                action: ["update"],
                identity: "/rest/v1/order/confirm/",
                name: "订单确认",
            }, {
                action: ["update"],
                identity: "/rest/v1/order/delivery/",
                name: "订单发货",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/skutype/",
                name: "sku类型",
            }, {
                action: ["get", "update", "delete", "add"],
                identity: "/rest/v1/skuvalue/",
                name: "sku值",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/analysis/orderamount/",
                name: "订单金额",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/analysis/ordercount/",
                name: "订单量",
            }, {
                action: ["get"],
                identity: "/rest/v1/php/dhf/store/pickpoint/",
                name: "自提点",
            }, {
                action: ["get"],
                identity: "/rest/v1/member/",
                name: "用户信息",
            }, {
                action: ["update"],
                identity: "rest/v1/order/discount/",
                name: "价格修改",
            }, {
                action: ["get"],
                identity: "/rest/v1/partner/",
                name: "查询公司",
            }, {
                action: ["get"],
                identity: "/rest/v1/phone/",
                name: "获取微信手机号",
            }, {
                action: ["add", "delete"],
                identity: "/rest/v1/tcos/",
                name: "新附件上传",
            }];
        }

        //查询角色详情
        $scope.roleOne = function() {
                dataService.roleOne($scope.role_id).then(function(one) {
                    console.error("one", one);
                    $scope.item = one;
                    $scope.istores = [];
                    $scope.user_wxstore = [];
                    if ($scope.item.data_range.store_ids) {
                        _.map($scope.item.data_range.store_ids, function(da, kk) {
                            var data = { store_ids: da };
                            $scope.istores.push(data);
                        });
                    }
                    if ($scope.item.data_range.app_ids) {
                        _.map($scope.item.data_range.app_ids, function(da, kk) {
                            var data = { app_ids: da };
                            $scope.istores.push(data);
                        });
                    }
                    if ($scope.item.data_range.store_range) {
                        _.map($scope.item.data_range.store_range, function(store, kk) {

                            var index = _.findIndex($scope.user_wxstore, { user_id: store.user_id })
                            if (index != -1) {
                                _.map(store.store_ids, function(da) {
                                    var data = { store_ids: da };
                                    $scope.user_wxstore[index].istores.push(data);

                                })
                            } else {
                                var stores = {
                                    user_id: Number(store.user_id),
                                    nick_name: store.nick_name,
                                    avatar: store.avatar,
                                    istores: []
                                }
                                _.map(store.store_ids, function(da) {
                                    var data = { store_ids: da };
                                    stores.istores.push(data);
                                })
                                $scope.user_wxstore.push(stores);

                            }
                        });
                    }
                    if ($scope.item.data_range.app_range) {
                        _.map($scope.item.data_range.app_range, function(store, kk) {

                            var index = _.findIndex($scope.user_wxstore, { user_id: store.user_id })
                            if (index != -1) {
                                _.map(store.app_ids, function(da) {
                                    var data = { app_ids: da };
                                    $scope.user_wxstore[index].istores.push(data);
                                })
                            } else {
                                var stores = {
                                    user_id: Number(store.user_id),
                                    nick_name: store.nick_name,
                                    avatar: store.avatar,
                                    istores: []
                                }
                                _.map(store.app_ids, function(da) {
                                    var data = { app_ids: da };
                                    stores.istores.push(data);
                                })
                                $scope.user_wxstore.push(stores);

                            }
                        });
                        _.map($scope.item.data_range.store_range, function(store, kk) {
                            var users_store = {
                                user_id: Number(store.user_id),
                                app_ids: []
                            }
                            _.map(store.app_ids, function(da) {
                                users_store.app_ids.push(da);

                            })
                            $scope.istores.push(users_store);
                        });
                        var data = {
                            app_range: $scope.item.data_range.app_range
                        }
                        $scope.istores.push(data);
                    }
                    console.error("isStores", $scope.istores, $scope.user_wxstore);
                    $scope.part_by_user = $scope.item.data_range.part_by_user ? 1 : 2;
                    if (!$scope.item.permissions) {
                        $scope.item.permissions = $scope.initpermissions;
                    }
                    //查询php附加权限
                    $scope.fujiaget();
                });
            }
            //添加权限
        $scope.AdditionalRole = function(type) {
            if (type) {
                var data1 = clone($scope.item.permissions);
                var data2 = clone($scope[type]);
                if (data1 && data2) {
                    $scope.item.permissions = concatData(data1, data2);
                    console.error("$scope.item.permissions", $scope.item.permissions);
                    //附加权限操作
                    $scope.addFjAry(type);
                } else {
                    $scope.addFjAry(type);
                }
            }
        }

        $scope.addFjAry = function(type) {
            var fjtype = 'fj' + type;
            var fjdata = clone($scope[fjtype]);
            if (type && fjdata) {
                $scope.fujiasaveresource(fjdata);
            }
        }

        //合并数组
        function concatData(arr1, arr2) {
            var arr = arr1.concat(arr2);
            var lastArr = [];
            for (var i = 0; i < arr.length; i++) {
                if (!unique(arr[i].identity, lastArr)) {
                    lastArr.push(arr[i]);
                }
            }
            return lastArr;
        }

        function unique(n, arr) {
            for (var i = 0; i < arr.length; i++) {
                if (n == arr[i].identity) {
                    return true;
                }
            }
            return false;
        }

        //保存
        $scope.saveData = function() {
            if ($scope.istores && !$scope.item.is_super_admin) {

                if (!$scope.item.permissions) {

                    return helper.myAlert("权限资源不能为空");
                }
                $scope.store_ids = [];
                $scope.app_ids = [];
                _.map($scope.istores, function(da, kk) {
                    console.error("kk", kk, da);
                    if (da.store_ids) {
                        $scope.store_ids.push(da.store_ids);
                    }
                    if (da.app_ids && da.app_ids.length) {
                        $scope.app_ids.push(da.app_ids);
                    }
                });
                $scope.item.data_range = _.extend({ store_ids: $scope.store_ids }, { app_ids: $scope.app_ids }, { part_by_user: $scope.part_by_user == 1 ? true : false });
            }
            if ($scope.user_wxstore && $scope.user_wxstore.length && !$scope.item.is_super_admin) {
                if (!$scope.item.permissions) {

                    return helper.myAlert("权限资源不能为空");
                }
                var users_store_range = [],
                    users_app_range = [],
                    user_stores = [],
                    user_apps = [];
                _.map($scope.user_wxstore, function(user) {
                    // console.error("kk", kk, da);

                    var store_ids = [];
                    var app_ids = [];
                    _.map(user.istores, function(da, kk) {
                        if (da.store_ids) {
                            store_ids.push(Number(da.store_ids));
                            if (_.indexOf(user_stores, da.store_ids) == -1) {
                                user_stores.push(Number(da.store_ids));
                            }
                        }
                        if (da.app_ids) {
                            app_ids.push(da.app_ids);
                            if (_.indexOf(user_apps, da.app_ids) == -1) {
                                user_apps.push(da.app_ids);
                            }
                        }
                    })
                    var user_store_data = {
                            user_id: Number(user.user_id),
                            nick_name: user.nick_name,
                            avatar: user.avatar,
                            store_ids: store_ids
                        },
                        user_app_data = {
                            user_id: Number(user.user_id),
                            nick_name: user.nick_name,
                            avatar: user.avatar,
                            app_ids: app_ids
                        };
                    users_store_range.push(user_store_data);
                    users_app_range.push(user_app_data);
                });
                $scope.item.data_range = _.extend({ store_range: users_store_range }, { app_range: users_app_range }, { part_by_user: $scope.part_by_user == 1 ? true : false }, { app_ids: $scope.app_ids }, { store_ids: $scope.store_ids });
            }
            if ($scope.item.is_super_admin) {
                $scope.item.permissions = [];
                $scope.item.data_range = '';
                $scope.item.menu = [];
            }
            console.error("isstore", $scope.istores, $scope.user_wxstore, $scope.item);
            // return false
            // $scope.item.data_range = _.extend({ store_ids: $scope.stores }, { app_ids: $scope.wxapp_ids });

            dataService.roleAdd($scope.item).then(function(result) {
                if (!result.Msg) {
                    $scope.phpPermissionAdd(result.role_id);
                    // helper.myAlert("success", "#/role/list");
                } else {
                    helper.message(result.Msg);
                }

            });
        }

        //接收插入permission
        $scope.addPermission = function(permission) {
            $scope.item.permission.push(permission);
        }

        //删除
        $scope.delAction = function(role_id) {
            helper.myConfirm("confirm operation", function() {
                dataService.roleDel(role_id).then(function(result) {
                    if (result && result.Msg) {
                        helper.message(result.Msg, "error");
                    } else {
                        $scope.getRoleList();
                    }
                });
            });
        }


        // 角色包含的用户列表
        $scope.userAction = function() {
            $scope.role_id = $location.search().role_id;
            $scope.roleuserList();
        }

        // 角色包含的用户列表
        $scope.adduser = function(open_id) {

            var data = {
                open_id: open_id,
                role_id: Number($scope.role_id)
            };
            dataService.bindAdd(data).then(function(rs) {
                $scope.roleuserList();
            })

            console.error("open_idopen_idopen_id", open_id);
        }
        $scope.addUserStore = function(open_id) {
            var that = this
            dataService.basicinfoGet({ open_id: open_id }).then(function(res) {
                if (res.user_id) {
                    if (_.findIndex($scope.user_wxstore, { user_id: res.user_id }) == -1) {
                        $scope.user_wxstore.push({
                            user_id: res.user_id,
                            nick_name: res.nick_name,
                            avatar: res.avatar_url,
                            istores: []
                        });
                    }
                }
            })
        }
        $scope.addUserStoreList = function(users) {
            if (users.length) {
                if ($scope.user_wxstore.length) {
                    _.map($scope.user_wxstore, function(wx_user, index) {
                        if (wx_user) {
                            var i = _.findIndex(users, { user_id: wx_user.user_id });
                            if (i == -1) {
                                $scope.user_wxstore.splice(index, 1);
                            }
                        }

                    })
                }
                _.map(users, function(user) {
                    if (!$scope.user_wxstore.length) {
                        $scope.user_wxstore = [];
                    }

                    var i = _.findIndex($scope.user_wxstore, { user_id: user.user_id });
                    if (i == -1) {
                        $scope.user_wxstore.push({
                            user_id: user.user_id,
                            nick_name: user.nick_name,
                            avatar: user.avatar,
                            istores: []
                        });
                    }
                })
                console.error("dd");
            }
        }
        $scope.deleteUsers = function(index) {
            console.error("index", index, $scope.user_wxstore);
            $scope.user_wxstore.splice(index, 1);
            // helper.myConfirm("确认删除吗", function(res) {
            //     // 
            // }, function() {

            // })

        }
        $scope.delete = function(index) {
            console.error("$scope", $scope.user_wxstore);
        }
        $scope.userList = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize
            };

            if ($scope.name) {
                query.query = { "name": $scope.name };
            }

            dataService.roleGet(query).then(function(list) {
                if (list) {
                    $scope.itemslist = list.roles;
                    $scope.itemsTotal = list.total_count;
                }
            });
        }


        //删除
        $scope.delbind = function(open_id) {
            helper.myConfirm("confirm operation", function() {
                dataService.bindDelete({ open_id: open_id, role_id: $scope.role_id }).then(function(result) {
                    if (!result.Msg) {
                        helper.message("success");
                        $scope.roleuserList();
                    } else {
                        helper.myAlert("success", "#/role/list");
                    }

                });
            });
        }

        $scope.roleuserList = function(pageNo) {
            // $scope.pageSize = 5;
            $scope.pageNo = pageNo ? pageNo : "1";
            var query = {
                page_no: $scope.pageNo,
                page_size: $scope.pageSize,
                role_id: $scope.role_id,
            };

            if ($scope.name) {
                query.query = { "name": $scope.name };
            }

            dataService.subuserGet(query).then(function(list) {
                if (list.users) {
                    $scope.itemslist = list.users;
                    $scope.itemsTotal = list.total_count;
                }
            });
        }

    }
})();